package server;

import java.util.HashMap;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import util.Receive;
import util.RouterHandler;

/** 
* @author SZQ 
* @Server
* @version 创建时间：2016年3月1日 下午5:40:01 
* 类说明 
*/
public class TCPServerHandler  extends SimpleChannelInboundHandler<Object> { 
	
	//每个TCP连接通道
	public  SocketChannel socketChannel;
	
	//通道和设备MAC映射表
	public TCPServerHandler(SocketChannel socketChannel) {
		this.socketChannel = socketChannel;
	}
	
	/**   
	 * @Description: TODO(用一句话描述该文件做什么) 
	 * @author SZQ   
	 * @date 2016年3月1日 下午5:44:31 
	 * @version V1.0   
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("Server  Receive....   " + msg );
		String data = msg.toString().trim();
		JSONObject ret = new JSONObject();
		if(data != null && data.length() > 0){
			Receive receive = new Receive(data);
			if("register".equals(receive.getFunc())){
					ret = deviceRegister(receive);
			}else{
				RouterHandler router = new RouterHandler();
				ret = router.execute(receive.getFunc(), receive.getData() );
			}
		}
		
		System.out.println("ret:--------------------------------------->" + ret);
		ctx.channel().writeAndFlush("server send  !" + ret);
	}

	
	/**   
	 * @Description: TODO(设备注册) 
	 * @author SZQ   
	 * @date 2016年3月9日 下午2:23:38 
	 * @version V1.0   
	 * @param receive 
	 */
	private JSONObject deviceRegister(Receive receive) {
		JSONObject ret = new JSONObject();
		ret.put("code", 0);
		ret.put("info", "success");
		JSONObject json = JSONObject.parseObject(receive.getData());
		String mac = json.getString("mac").trim();
		HashMap<String, Object> channelMap = CMDServer.getChannelMap();
		if (!channelMap.containsKey("mac")) {
			channelMap.put(mac, socketChannel);
		}
		return ret;
	}

	@Override
	    public void exceptionCaught(ChannelHandlerContext ctx,
	            Throwable cause) throws Exception {
	        ctx.close();
	    }
}
